import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import "./assets/style/index.css";
import bus from "./utils/eventBus";
import hasBtn from "./utils/hasBtn";

Vue.use(ElementUI);
Vue.config.productionTip = false;

Vue.prototype.$bus = bus;

// 配置全局路由守卫
router.beforeEach((to, form, next) => {
  // 判断本地是否有 token 没有的话跳转到 login 页面
  let token = localStorage.getItem("token");

  // 用户进入 login 页面直接放行
  if (to.path === "/login") {
    next();
  } else {
    // 用户进入其他页面，判断有没有token，有的话放行，没有就跳转到 login 组件
    if (token) {
      // 解决当用户登陆成功后每次刷新权限菜单数组会清空问题
      if (store.state.menuList && store.state.menuList.length === 0) {
        // 重新执行 actions 内函数重新渲染
        store.dispatch("SET_SIDEMENU").then(() => {
          // 渲染完成后放行到主页
          next({ path: to.path });
        });
      } else {
        next();
      }
    } else {
      next({ path: "/login" });
    }
  }
});

// 后置钩子处理面包屑导航
router.afterEach((to, from) => {
  let reset = [];
  for (let i = 1, len = to.matched.length; i < len; i++) {
    reset.push(to.matched[i]);
  }
  store.commit("GET_BREADCRUMB", reset);
});

// 设置鉴权按钮自定义指令
Vue.directive("has", {
  inserted(el, binding) {
    // 获取本地按钮权限数组
    let buttons = JSON.parse(localStorage.getItem("userInfo")).permission
      .buttons;
    // 指令传的value
    let bdValue = binding.value;
    // 如果没有权限那就隐藏按钮
    if (!hasBtn(buttons, bdValue)) {
      el.style.display = "none";
    }
  },
});

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");
